<?php
namespace Mobile\Controller;

class OilcardController extends MobileController {
    /**
    * 获取油卡类型列表
    * 
    */
    public function type(){
        if(empty($this->uid)){
            $this->err('用户未登录!');
        }
        $model = M('OilCardtype');
        $where['status'] = array('egt',0);
        $res = $model->where($where)->field('typeid,typename')->select();
        $this->succ($res);
    }
    
    /**
    * 获取油卡列表
    * 
    */
    public function index($p=1,$limit=10){
        if(empty($this->uid)){
            $this->err('用户未登录!');
        }
        $model = M('UserOilcard');
        $modelType = M('OilCardtype');
        $where['uid'] = $this->uid;
        $where['status'] = array('egt',0);
        $count = $model->where($where)->count();
        $resCar = $model->field('uid,status',true)->where($where)->page($p,$limit)->select();
        foreach($resCar as &$row){
            $row['typename'] = $modelType->cache(true)->where('typeid='.$row['cardtype'])->getField('typename');
        }
        
        $ret = array(
            'count'=>$count,
            'data'=>$resCar,
        );
        
        $this->succ($ret);
    }
    
    
    /**
    * 添加或编辑油卡
    * 
    */
    public function edit(){
        if(empty($this->uid)){
            $this->err('用户未登录!');
        }

        $model = M('UserOilcard');
        $data = $model->create();
        $card_id = I('card_id');
        if(!empty($card_id)){
            //检测是否属于该用户
            $where['card_id'] = $card_id;
            $where['uid'] = $this->uid;
            
            $model->where($where)->save($data);
        }else{
            $data['uid'] = $this->uid;
            $card_id = $model->add($data);
        }
        unset($where);
        $where['card_id'] = $card_id;
        $where['uid'] = $this->uid;
        
        $res = $model->field('uid,status',true)->where($where)->find();
        if($res){
            $modelType = M('OilCardtype');
            $res['typename'] = $modelType->cache(true)->where('typeid='.$res['cardtype'])->getField('typename');
        }
        $this->succ($res);
    }
    
    /**
    * 删除油卡
    * 
    * @param mixed $card_id
    */
    public function del($card_id){
        if(empty($this->uid)){
            $this->err('用户未登录!');
        }
        if(empty($card_id)){
            $this->err('未指定车辆!');
        }

        $model = M('UserOilcard');
        $where['card_id'] = $card_id;
        $where['uid'] = $this->uid;
        $data['status'] = -1;
        $model->where($where)->save($data);
        $this->succ('删除成功！');
    }
}